package com.app.medicalcontrol.fragment.Robot.child;

import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.transition.Fade;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.app.medicalcontrol.R;
import com.app.medicalcontrol.basis.BasisFragment;
import com.app.medicalcontrol.basis.Constants;
import com.app.medicalcontrol.bean.BaseListBean;
import com.app.medicalcontrol.bean.LoginBean;
import com.app.medicalcontrol.bean.MessageListBean;
import com.app.medicalcontrol.bean.Robot;
import com.app.medicalcontrol.bean.RobotListBean;
import com.app.medicalcontrol.event.RobotListRefreshEvent;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.loopj.android.http.RequestParams;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import my.http.HttpRestClient;
import my.http.MyHttpListener;

/**
 * Created by otis on 2018/4/11.
 */

public class RobotListFragment extends BasisFragment {

    @BindView(R.id.recyclerview)
    XRecyclerView mRecyclerView;
    private MyAdapterList mAdapter;
    private RobotListBean mListBean;
    public static final int REQ_MODIFY_FRAGMENT = 96;
    @BindView(R.id.refresh_view)
    View refreshView;

    @Override
    public void initViews() {
        super.initViews();
        setContentView(R.layout.base_xrecycler_with_top);
        refreshView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mRecyclerView.refresh();
            }
        });
        setTitle("设备管理");
        setTitleRightButton(R.mipmap.top_icon_msg, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getMessageInfo(v);
            }
        });
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        initRecycler();
        mListBean = new RobotListBean();
        getList();
        getMessageInfo();
    }

    public void getMessageInfo() {
        showLoading();
        RequestParams params = new RequestParams();
        HttpRestClient.post(Constants.URL_MESSAGE_LIST, params, new MyHttpListener() {
            @Override
            public void onSuccess(int httpWhat, Object result) {
                MessageListBean listBean = (MessageListBean) result;
                if (listBean.getUnread_count() > 0) {
                    showRedCircle();
                }
            }

            @Override
            public void onFinish(int httpWhat) {
                hideLoading();
            }
        }, 0, MessageListBean.class);
    }


    private void getList() {
        showLoading();
        RequestParams params = new RequestParams();
        params.put("store_id", LoginBean.getInstance().getStore_id());
        params.put(BaseListBean.PAGE_NAME, mListBean.getCurrentPage());
        params.put(BaseListBean.PAGE_SIZE_NAME, BaseListBean.PAGE_SIZE);
        HttpRestClient.get(Constants.URL_ROBOT_LIST, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        RobotListBean bean = (RobotListBean) result;
                        mListBean.addListBean(bean);
                        setListView();
                    }

                    @Override
                    public void onFinish(int httpWhat) {
                        hideLoading();
                        onListViewComplete();
                    }
                },
                0, RobotListBean.class);
    }

    private void initRecycler() {
        mRecyclerView.setVerticalScrollBarEnabled(true);
        mRecyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2));
        mRecyclerView.setEmptyView(refreshView);
        mRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallRotate);
        mRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                mListBean.refresh();
                getList();
            }

            @Override
            public void onLoadMore() {
                getList();
            }
        });
        mRecyclerView.setPullRefreshEnabled(true);
    }

    private void onListViewComplete() {
        mRecyclerView.refreshComplete();
        mRecyclerView.loadMoreComplete();
        mRecyclerView.setLoadingMoreEnabled(mListBean.hasNextPage());
    }

    private void setListView() {
        if (mAdapter == null) {
            mAdapter = new MyAdapterList();
            mRecyclerView.setAdapter(mAdapter);
        } else {
            mAdapter.notifyDataSetChanged();
        }
    }

    public class MyAdapterList extends RecyclerView.Adapter<MyAdapterList.ViewHolder> {

        public MyAdapterList() {

        }

        //创建新View，被LayoutManager所调用
        @Override
        public MyAdapterList.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.fragment_list_robot, viewGroup, false);
            return new MyAdapterList.ViewHolder(view);
        }


        //将数据与界面进行绑定的操作
        @Override
        public void onBindViewHolder(MyAdapterList.ViewHolder viewHolder, int position) {
            Robot data = mListBean.getData().get(position);
            viewHolder.listItem.setTag(data);
            viewHolder.robotName.setText(data.getName());
            viewHolder.wifiBtn.setSelected(data.checkFromInt(data.getIs_wifi()));

            //设置图片
            viewHolder.startBtn.setChecked(data.checkFromInt(data.getStart_status()));
            viewHolder.serverBtn.setChecked(data.checkFromInt(data.getWork_status()));
            viewHolder.wareBtn.setChecked(data.checkFromInt(data.getHardware_status()));
            //设置文字
            viewHolder.startBtn.setText(data.startOrCloseFromInt(data.getStart_status()));
            viewHolder.serverBtn.setText(data.serverStatusFromInt(data.getWork_status()));
            viewHolder.wareBtn.setText(data.wareStatusFromInt(data.getHardware_status()));
        }

        //获取数据的数量
        @Override
        public int getItemCount() {
            return mListBean.getData() == null ? 0 : mListBean.getData().size();
        }

        //自定义的ViewHolder，持有每个Item的的所有界面元素
        public class ViewHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.tv_robot_name)
            public TextView robotName;
            @BindView(R.id.list_item)
            public LinearLayout listItem;
            @BindView(R.id.rb_wifi)
            public Button wifiBtn;
            //            @BindView(R.id.rb_blue_tooth)
//            public Button blueToothBtn;
            @BindView(R.id.rb_start)
            public RadioButton startBtn;
            @BindView(R.id.rb_server_status)
            public RadioButton serverBtn;
            @BindView(R.id.rb_ware_status)
            public RadioButton wareBtn;

            public ViewHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);
                listItem.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Robot data = (Robot) listItem.getTag();
                        RobotItemFragment fragment = RobotItemFragment.newInstance(data.getRobot_id());
                        // 这里是使用SharedElement的用例
                        // LOLLIPOP(5.0)系统的 SharedElement支持有 系统BUG， 这里判断大于 > LOLLIPOP
                        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
                            setExitTransition(new Fade());
                            fragment.setEnterTransition(new Fade());
                            // 25.1.0以下的support包,Material过渡动画只有在进栈时有,返回时没有;
                            // 25.1.0+的support包，SharedElement正常
                            extraTransaction().startForResult(fragment, REQ_MODIFY_FRAGMENT);
                        } else {
                            startForResult(fragment, REQ_MODIFY_FRAGMENT);
                        }
                    }
                });

//                wifiBtn.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        Robot data = (Robot) wifiBtn.getTag();
//                        wifiBtn.setSelected(!wifiBtn.isSelected());
////                        startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS)); //直接进入手机中的wifi网络设置界面
//                    }
//                });

            }
        }
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
        if (requestCode == REQ_MODIFY_FRAGMENT) {
            //设备管理信息返回  do something
            mListBean.refresh();
            getList();
        }
    }

    //订阅方法，当接收到事件的时候，会调用该方法
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(RobotListRefreshEvent messageEvent) {
        mListBean.refresh();
        getList();
    }

}
